<template>
  <div v-loading="loading" class="fee_set" element-loading-text="加载中...">
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="handleAddFee"> 添加工单费用 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeStatus(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <el-input
          v-model.trim="name"
          placeholder="名称搜索"
          clearable
          @keyup.enter="getList"
          @clear="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>
    <div class="table_container">
      <el-table
        ref="tableDom"
        border
        stripe
        resizable
        :data="tableData"
        height="100%"
        @selection-change="handleChange"
      >
        <!-- 选择 -->
        <el-table-column type="selection" width="40" fixed="left" :align="'center'" />

        <!-- 序号 -->
        <el-table-column
          show-overflow-tooltip
          type="index"
          :index="indexMethod"
          label="序号"
          width="50"
          :align="'center'"
          fixed="left"
        />

        <!-- 费用名称 -->
        <el-table-column show-overflow-tooltip prop="name" label="费用名称" min-width="200" />

        <!-- 费用金额 -->
        <el-table-column show-overflow-tooltip prop="price" label="费用金额" width="120">
          <template #default="scope">
            <span>￥{{ scope.row.price }}</span>
          </template>
        </el-table-column>

        <!-- 修改金额 -->
        <el-table-column show-overflow-tooltip prop="updatePrice" label="修改金额" width="80">
          <template #default="scope">
            <span v-if="!scope.row.updatePrice">不允许</span>
            <span v-if="scope.row.updatePrice">允许</span>
          </template>
        </el-table-column>

        <!-- 创建时间 -->
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />

        <!-- 更新时间 -->
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />

        <!-- 状态 -->
        <el-table-column prop="status" label="状态" width="70" :align="'center'" fixed="right">
          <template #default="scope">
            <div class="flex_justify_center">
              <HStatus v-if="!scope.row.status">启用</HStatus>
              <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
            </div>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column fixed="right" label="操作" width="90">
          <template #default="scope">
            <h-space>
              <HLink @click="handleEditFee(scope.row.id)">编辑</HLink>
              <h-link type="error" @click="handleDelFeeSet(scope.row)">删除</h-link>
            </h-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <Pagination
        ref="pagination"
        :list_total="total"
        @size-change="getList"
        @current-change="getList(false)"
      />
    </div>

    <!-- 添加/编辑  费用弹窗 -->
    <h-dialog
      v-model="addDialog"
      :title="feeForm.id ? '编辑费用' : '添加费用'"
      :loading="getFeeDetailLaoding || feeFormSaveLoading"
      @close="closeFeeModal"
    >
      <el-form
        ref="feeFormInstance"
        label-position="top"
        inline-message
        class="modal_form_content"
        :rules="rules"
        :model="feeForm"
      >
        <!-- 费用名称 -->
        <el-form-item label="费用名称" prop="name">
          <el-input v-model.trim="feeForm.name" clearable placeholder="请输入名称" maxlength="10" />
        </el-form-item>

        <!-- 是否为远程费 -->
        <el-form-item
          label="是否为远程费"
          prop="enableRemoteFees"
          class="swtich-container-size-small"
        >
          <el-switch
            v-model="feeForm.enableRemoteFees"
            size="small"
            @change="handleEnableRemoteChange"
          />
          <div class="text">
            {{ feeForm.enableRemoteFees ? '是' : '否' }}
            <el-tooltip content="若开启，申请费用需要填写公里数" placement="top">
              <i class="iconfont icon-warning"></i>
            </el-tooltip>
          </div>
        </el-form-item>

        <!-- 公里数 -->
        <!-- <el-form-item label="公里数" v-if="feeForm.enableRemoteFees">
          <el-input model-value="申请费用时填写" disabled></el-input>
        </el-form-item> -->

        <!-- 费用金额 -->
        <el-form-item v-if="feeForm.enableRemoteFees" label="费用金额" prop="price">
          <el-input clearable disabled placeholder="远程费金额在填写公里数后自动计算" />
        </el-form-item>
        <el-form-item v-else label="费用金额" prop="price">
          <el-input
            v-model.trim="feeForm.price"
            clearable
            placeholder="请输入金额"
            :disabled="!feeForm.updatePrice"
            @input="() => (feeForm.price = amountForamt(String(feeForm.price)))"
          />
        </el-form-item>

        <div class="same_line">
          <!-- 费用状态 -->
          <el-form-item label="费用状态" class="same_line">
            <el-radio-group v-model="feeForm.status">
              <el-radio :value="false" size="small">启用</el-radio>
              <el-radio :value="true" size="small">禁用</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 修改金额 -->
          <el-form-item label="修改金额" class="same_line">
            <el-radio-group v-model="feeForm.updatePrice">
              <el-radio :value="true" size="small">允许</el-radio>
              <el-radio :value="false" size="small">不允许</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </el-form>

      <template #footer>
        <HButton is-modal type="primary" @click="onFeeFormSave">保存</HButton>
        <HButton is-modal @click="closeFeeModal">取消</HButton>
      </template>
    </h-dialog>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, reactive, onMounted } from 'vue'
  import { Search, Warning, Delete, CircleCheck, ArrowDown } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, TableInstance } from 'element-plus'
  import { feeSave, feeGetList, feeGetDetail, feeDisable, feeDelete } from '@/api/basic'
  import { FeeSet } from './types'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import { amountForamt } from '@/utils/tools'

  const handleDelFeeSet = (feeSet: FeeSet) => {
    if (tableDom.value) {
      tableDom.value.clearSelection()
      tableDom.value.toggleRowSelection(feeSet, true)
      changeStatus(3)
    }
  }

  const loading = ref(false)
  const addDialog = ref(false)
  const name = ref('') // 名称

  const tableData = ref([]) // 列表数据
  const tableDom = ref<TableInstance | null>(null) // 列表dom

  const pagination = ref() // 分页dom
  const total = ref(0) // 总数目

  // 表单元素
  const feeFormInstance = ref<FormInstance | null>(null)

  // 费用表单
  const feeForm = ref<OrderAPIRequest.FeeForm>({
    id: '',
    name: '',
    price: 1,
    status: false,
    updatePrice: true,
    enableRemoteFees: false,
    kilometers: 0,
  })

  // 获取费用详情加载
  const getFeeDetailLaoding = ref(false)

  // 费用表单保存加载
  const feeFormSaveLoading = ref(false)

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入费用名称', trigger: 'blur' }],
    price: [{ required: true, message: '请输入费用金额', trigger: 'blur' }],
  })

  // 列表序号
  const indexMethod = (index: number) => {
    return index + 1
  }

  // 获取分页数据
  const getPageData = (val) => {
    if (val) pagination.value.setPage()
    return {
      limit: pagination.value.size,
      name: name.value,
      page: pagination.value.current,
    }
  }

  // 获取列表数据
  const getList = async (val = true) => {
    loading.value = true
    await feeGetList(getPageData(val)).then((res) => {
      tableData.value = res.data.data.rows
      total.value = parseInt(res.data.data.total)
    })
    loading.value = false
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  /**
   * 添加费用
   */
  const handleAddFee = () => {
    feeForm.value.id = null
    feeForm.value.name = ''
    feeForm.value.price = 1
    feeForm.value.status = false
    feeForm.value.updatePrice = true
    feeForm.value.enableRemoteFees = false
    feeForm.value.kilometers = 0
    addDialog.value = true
  }

  /**
   * 编辑费用
   * @param {String} id - 费用id
   */
  const handleEditFee = async (id: string) => {
    addDialog.value = true
    getFeeDetailLaoding.value = true
    const res = await feeGetDetail(id)
    feeForm.value = {
      id: res.data.data.row.id,
      name: res.data.data.row.name,
      price: res.data.data.row.price,
      status: res.data.data.row.status,
      updatePrice: res.data.data.row.updatePrice,
      kilometers: res.data.data.row.kilometers,
      enableRemoteFees: res.data.data.row.enableRemoteFees,
    }
    getFeeDetailLaoding.value = false
  }

  /**
   * 费用保存事件
   */
  const onFeeFormSave = async () => {
    if (!feeFormInstance.value) {
      return
    }

    try {
      await feeFormInstance.value.validate()
      feeFormSaveLoading.value = true
      const res = await feeSave(feeForm.value)
      feeFormSaveLoading.value = false
      if (res.data.code === 20000) {
        HMessage.success(infoTip.order.fee.save_success)
        closeFeeModal()
        getList()
        return
      }

      HMessageBox.error(infoTip.order.fee.err_code[res.data.code] || res.data.message)
    } catch (error) {
      // error
    }
  }

  /**
   * 是否为远程费选择事件
   */
  const handleEnableRemoteChange = () => {
    if (feeForm.value.enableRemoteFees) {
      feeForm.value.price = 0
    }
  }

  /**
   * 初始化费用表单
   */
  const initFeeForm = () => {
    feeForm.value = {
      id: '',
      name: '',
      price: 1,
      status: false,
      updatePrice: true,
      enableRemoteFees: false,
      kilometers: 0,
    }
  }

  /**
   * 关闭费用弹窗
   */
  const closeFeeModal = () => {
    addDialog.value = false
    initFeeForm()
  }

  // 修改状态方法
  const changeMethod = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的费用项目`,
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    ElMessageBox({
      type: type === '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确定${type}选中的费用项目?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'error',
            duration: 5000,
            plain: true,
            showClose: true,
          })
        })
      } else {
        await method(arr).then((res) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'error',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          if (dialog != '') {
            addDialog.value = false
          }
        })
      }
      selecttion.value = []
      tableDom.value.clearSelection()
      getList()
    })
  }

  // 批量启用/禁用/删除
  const changeStatus = (n) => {
    if (n == 1) {
      changeMethod('启用', feeDisable, selecttion.value, false, '')
    }
    if (n == 2) {
      changeMethod('禁用', feeDisable, selecttion.value, true, '')
    }
    if (n == 3) {
      changeMethod('删除', feeDelete, selecttion.value, 3, '')
    }
    if (n == 4) {
      changeMethod('删除', feeDelete, [feeForm.value.id], 3, addDialog)
    }
  }

  onMounted(() => {
    getList()
  })

  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import '../../index.scss';

  .icon-warning {
    color: $secondColor2;
  }
</style>
